<template>
	<view class="container">
		<view class="top">
			<view class="title">{{  categoryName }}</view>
			<view class="iconfont icon-shoucang" @click="addCollect" v-if="!currQues.isCollect"></view>
			<view class="iconfont icon-shoucang-filled" @click="delCollect" v-else></view>
		</view>
		<swiper :current="currentIndex" @change="onSwiperChange" class="swiper-container">
			<swiper-item v-for="(question, index) in questions" :key="index" class="swiper-item">
				<view class="question-item">
					<view class="question-item-top">
						<view class="type">{{ question.type === 'single' ? '单选题' : '多选题' }}</view>
						<view>{{ index + 1 }}/{{ totalNum }}</view>
					</view>
					<view class="question-item-text">{{ question.question }}</view>
					<view class="question-item-options">
						<view
							class="option-item" 
							v-for="(option, optIndex) in question.options" 
							:key="optIndex"
							:class="{ active: selectedOptions[index] === optIndex || (question.user_option === option) }"
							@click="selectOption(index, optIndex, question, option)"
						>
							{{ option }}
						</view>
					</view>
					<view class="question-item-desc" v-if="question.user_option">
						<view v-if="question.user_option === question.answer">回答正确。</view>
						<view v-else>回答错误，正确答案：{{ question.answer }}。</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
		<view class="action">
			<button class="btn btn-pre" @click="prevQuestion" v-if="currentIndex > 0">上一题</button>
			<button class="btn btn-next" @click="nextQuestion" v-if="currentIndex < (totalNum - 1)">下一题</button>
			<button class="btn btn-next" @click="goBack" v-if="currentIndex === (totalNum - 1)">返回</button>
		</view>
		
		
		<!-- 收藏列表 -->
		<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff" @change="change">
		    <FavoritePop @close="close" @open="open" :folderList="folderList" :id="currQues?.id" :articleItem="currQues" :module="2"></FavoritePop>
		</uni-popup>
		<!-- 新增 -->
		<uni-popup ref="addFolderPop" :mask-click="false">
		    <view class="addNewFolder-container">
		        <view class="title">新建收藏夹</view>
		        <input class="folderName" type="text" placeholder="请输入收藏夹名称" :adjust-position="false"
		            v-model="folderName">
		        <view class="footer">
		            <view @tap="hide" class="cancel">取消</view>
		            <view @tap="addFolder" class="confirm">确定</view>
		        </view>
		    </view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { API_getChoiceQuestion, API_submitAnswer } from '@/service/home';
import { API_removeCollection, API_getFolder, API_addFolder } from '@/service/favorite';
import FavoritePop from '@/components/FavoritePop.vue';
import type { Folder } from '@/type/favorite';

const emit = defineEmits(['favoritePopup', 'sendSuccess']);
const category = ref<number>(0);
const categoryName = ref<string>('');
const totalNum = ref<number>(0);
const questions = ref<Array<any>>([]);
const currentIndex = ref(0);
const currQues = ref<any>({});
const selectedOptions = reactive(Array(questions.value.length).fill(null));
//控制弹出层显示
const addFolderPop = ref<any>("");
const folderName = ref<string>("");
const popup = ref<any>("");
const input = ref<string>('');
const bottom = ref<number>(0);
const folderList = ref<Folder[]>([]);

const nextQuestion = () => {
	if (currentIndex.value < totalNum.value - 1) {
		currentIndex.value++;
		getChoiceQuestion(currentIndex.value + 1);
	}
};

const prevQuestion = () => {
	if (currentIndex.value > 0) {
		currentIndex.value--;
		getChoiceQuestion(currentIndex.value + 1);
	}
};

const goBack = () => {
	uni.navigateBack();
}

const getCurrTime = () => {
	const stamp = new Date().getTime() + 8 * 60 * 60 * 1000;
	const beijingTime = new Date(stamp).toISOString().replace(/T/, ' ').replace(/\..+/, '').substring(0, 19);
	return beijingTime; 
}

const selectOption = (questionIndex: number, optionIndex: number, question: any, option: string) => {
	if(question.user_option) return false;
	
	selectedOptions[questionIndex] = optionIndex;
	submitAnswer(question.id, option, getCurrTime());
};

const submitAnswer = async (id: number, answer: string, choice_time: string) => {
	const res = await API_submitAnswer(id, answer, choice_time);
	if(res.data) {
		const resData: any = res.data;
		uni.showToast({
			title: resData.isCorrect ? '回答正确' : '回答错误',
			icon:'none'
		})
		nextQuestion();
	}
}

const onSwiperChange = (e: any) => {
	currentIndex.value = e.detail.current;
};

const getChoiceQuestion = async (page: number) => {
	const res = await API_getChoiceQuestion(category.value, page);
	if(res.data) {
		const resData = res.data;
		let options = resData.options.split(' ');
		questions.value.push({...resData, options: options})
		currQues.value = questions.value[currentIndex.value];
	}
}
 
// 收藏
const addCollect = async () => {
	popup.value.open();
	const res = await API_getFolder(2);
	folderList.value = res.data;
}

// 取消收藏
const delCollect = async () => {
	const res = await API_removeCollection({
		'content_id': currQues.value.id,
		'module': 2
	});
	
	if (res.code === 1) {
	    uni.showToast({
	        title: '取消收藏成功',
	        icon: 'none',
	        mask: true
	    })
	    currQues.value.isCollect = false;
	} else {
	    uni.showToast({
	        title: '取消收藏失败',
	        icon: 'none',
	        mask: true
	    })
	}
}

//新建收藏夹
const addFolder = async () => {
    for (let i = 0; i < folderList.value.length; i++) {
        if (folderList.value[i].collectionName === folderName.value) {
            uni.showToast({
                title: '收藏夹名称不能重复',
                icon: 'none',
                mask: true
            })
            return;
        }
    }
	
    let res = await API_addFolder({
        collection_name: folderName.value,
        create_time: getCurrTime(),
        module: 2
    })
    if (res.code === 1) {
        uni.showToast({
            title: '新建成功',
            icon: 'success',
            mask: true
        })
        addCollect();

    } else {
        uni.showToast({
            title: '新建失败',
            icon: 'none',
            mask: true
        })
    }
    hide();
    folderName.value = "";
}

// 防止滚动穿透
const change = (e: any) => {
    emit('favoritePopup', e.show);
}
// 关闭收藏列表pop
const close = (favorite: boolean | null) => {
    if (favorite != null) {
		currQues.value.isCollect = favorite;
    }
    popup.value.close();

}

// 打开新建收藏pop
const open = async () => {
    addFolderPop.value.open();
}
// 关闭新建收藏夹列表
const hide = () => {
    addFolderPop.value.close();
}

// onLoad((options) => {
// 	if(options.id) {
// 		getIntegratedQuestion(options.id);
// 	}
// })

onLoad((options) => {
	if(!options?.category) {
		uni.navigateBack();
	} else {
		category.value = options.category;
		totalNum.value = options.totalNum;
		categoryName.value = options.categoryName;
		getChoiceQuestion(1);
	}
})
</script>





<style scoped lang="scss">


.container {
	position: relative;
	width: 100%;
	height: 100vh;
	padding: 30rpx;
	box-sizing: border-box;
	background-color: #fff;
	display: flex;
	flex-direction: column;
}

.top {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 40rpx;
	margin-bottom: 30rpx;
	.title {
		color: #101010;
	}
	.iconfont {
		font-size: 40rpx;
	}
}

.swiper-container {
	flex: 1; // 确保swiper占据剩余空间
}

.swiper-item {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
}

.question-item {
	width: 100%;
	height: 100%;
	padding: 20rpx;
	box-sizing: border-box;
	overflow-y: auto;
	.question-item-top {
		display: flex;
		justify-content: space-between;
		color: $color-main;
		font-size: 28rpx;
		.type {
			padding: 0 10rpx;
			border: 2rpx solid $color-main;
			border-radius: 30rpx;
		}
	}
	.question-item-text,
	.question-item-desc {
		color: #101010;
		font-size: 28rpx;
		line-height: 56rpx;
		margin: 20rpx 0;
	}
	.question-item-options {
		.option-item {
			padding: 0 40rpx;
			height: 64rpx;
			line-height: 64rpx;
			font-size: 28rpx;
			margin-bottom: 30rpx;
			background-color: #eee;
			border-radius: 16rpx;
			&.active {
				background-color: $color-main;
				color: #fff;
			}
		}
	}
}

.action {
	width: 100%;
	display: flex;
	justify-content: center;
	gap: 40px;
	margin-top: 20rpx; // 给按钮一些上边距
	.btn {
		flex: 1;
		font-size: 30rpx;
		text-align: center;
		outline: none;
		border-radius: 10rpx;
		// margin: 0 40rpx;
	}
	.btn-pre {
		background-color: #fff;
		border: 2rpx solid $color-main;
		color: $color-main;
		&:disabled {
			border-color: #ccc;
			color: #ccc;
		}
	}
	.btn-next {
		background-color: $color-main;
		color: #fff;
		&:disabled {
			background-color: #ccc;
		}
	}
}

.addNewFolder-container {
    position: fixed;
    width: 500rpx;
    left: calc(50vw - 250rpx);
    bottom: calc(50vh);
    border: 1rpx solid #ddd;
    background: #fff;
    border-radius: 10rpx;
    font-size: 30rpx;

    .title {
        padding-top: 30rpx;
        text-align: center;
        font-weight: 700;
    }

    .folderName {
        margin: 30rpx;
        padding: 10rpx;
        border: 1rpx solid #ddd;
        border-radius: 20rpx;
    }

    .footer {
        display: flex;
        // justify-content: space-around;
        // align-items: center;
        border-top: 1rpx solid #ddd;


        .cancel {
            padding: 20rpx 0;
            flex: 1;
            text-align: center;
        }

        .confirm {
            padding: 20rpx 0;
            flex: 1;
            text-align: center;
            border-left: 1rpx solid #ddd;
            color: $color-main;
        }

    }
}
</style>
